package com.picturehistory.core.jersey.services;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.picturehistory.core.jersey.dao.UserDAO;
import com.picturehistory.core.jersey.exception.InvalidPinException;
import com.picturehistory.core.jersey.exception.InvalidUserException;
import com.picturehistory.core.jersey.model.User;
import com.picturehistory.core.jersey.util.PIN;
import com.picturehistory.core.jersey.util.Response;

@Service
public class UserService {

	private final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	@Autowired
	private UserDAO dao;
	
	public PIN store(String userId, String password, String idNumber, String deviceSN) {
		
		User user = null;
		try {
			user = new User(userId, password, idNumber, deviceSN);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Key key = KeyFactory.createKey(User.class.getSimpleName(), "user:"+userId);
		user.setKey(key);
		try {
			dao.storeUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		PIN ret = new PIN();
		//
		ret.setResult(PIN.OK);
		ret.setMessage("successfully created a new user");
		ret.setPin(new String(user.getPin()));
		ret.setCreated(new Date());
		//ret.setExpired(expired)
		
		return ret;
	}
	
	public User getUserByIdNumber(String idNumber) {
		return dao.getUserByIdNumber(idNumber);
	}
	
	public User getUserByUserId(String userId) {
		return dao.getUserByUserId(userId);
	}
	
	public User getDetachedUserByUserId(String userId) {
		return dao.getDetachedUserByUserId(userId);
	}
	
	public PIN login(String idNumber, String pin) throws InvalidUserException, InvalidPinException {
		
		User user = dao.getUserByIdNumber(idNumber);
		if (user == null) {
			throw new InvalidUserException("User does NOT exist");
		}
		
		logger.info(user.toString());
		PIN newPin = user.login(pin);
		
		if (newPin == null) {
			throw new InvalidPinException("PIN is not valid");
		}
		
		dao.storeUser(user);
		return newPin;
	}

	public PIN validateUser(String userId, String password) {
		
		User user = dao.getDetachedUserByUserId(userId);
		return null;
	}
}
